"""
脚本作为处理 json 数据主程序，将 json 数据拼接 url 组合为资源链接；
将链接进行 URL 编码
"""
import json
import urllib.parse
import sys
import os
import logging

# 重新配置标准输出的编码为 UTF-8
sys.stdout.reconfigure(encoding='utf-8')
sys.stderr.reconfigure(encoding='utf-8')


logging.basicConfig(level=logging.INFO,
                    format='[%(asctime)s %(levelname)s]: %(message)s',
                    datefmt = '%Y-%m-%d %H:%M:%S')

def extract_paths(json_data):
    paths = []


    def traverse(data, current_path):
        for item in data:
            new_path = current_path + [item["name"]]
            if "children" in item:
                traverse(item["children"], new_path)
            else:
                paths.append("/".join(new_path))


    traverse(json_data["children"], [])
    return paths


def encode_path(path):
    encoded_parts = []
    for part in path.split('/'):
        encoded_parts.append(urllib.parse.quote(part))
    return '/'.join(encoded_parts)


with open('list.json', 'r', encoding='utf-8') as file:
    json_data = json.load(file)


url = "https://down.52pojie.cn/"
paths = extract_paths(json_data)
downloads = []
for path in paths:
    encoded_path = encode_path(path)
    download_url = url + encoded_path + '\n'
    downloads.append(download_url)

# 拼接文件路径
file_path = os.path.join('Data', 'download.txt')
# 获取文件所在目录路径
dir_path = os.path.dirname(file_path)
# 如果目录不存在，创建目录
if not os.path.exists(dir_path):
    os.makedirs(dir_path)
# 以写入模式打开文件
with open(file_path, 'w', encoding='utf-8') as file:
    for download_url in downloads:
        file.write(download_url)
        
logging.info('链接处理完成')